import pymongo



class MongoHelper():
    def __init__(self):
        self.client = pymongo.MongoClient('mongodb://47.94.105.135:27017/',connect=False)
        self.params = {'chapterUrl': None, 'chapterName': None, 'chapterID': None,
                        'chapterContent': None
                        }
    def init_db(self, tabelName):
        if tabelName:
            #表示连接Test数据库
            self.db = self.client["HiXiaoShuo"]
            #表示Test数据库下面的tests表
            self.tests = self.db[tabelName]
    def drop_db(self):
        self.client.drop_database(self.db)
    def insert(self, value=None):
        if value:
            proxy = dict(chapterID=value['chapterID'],chapterUrl=value['chapterUrl'], chapterName=value['chapterName'], chapterContent=value['chapterContent'])
            #给数据库插入数据
            self.tests.insert(proxy)

    def update(self, conditions=None, value=None):
        if conditions and value:
            self.tests.update(conditions, {"$set": value})
            return {'updateNum': 'ok'}
        else:
            return {'updateNum': 'fail'}

    def select(self, count=None, conditions=None):
        if count:
            count = int(count)
        else:
            count = 0
        if conditions:
            conditions = dict(conditions)
            conditions_name = ['types', 'protocol']
            for condition_name in conditions_name:
                value = conditions.get(condition_name, None)
                if value:
                    conditions[condition_name] = int(value)
        else:
            conditions = {}
        items = self.tests.find(conditions, limit=count).sort(
            [("speed", pymongo.ASCENDING), ("score", pymongo.DESCENDING)])
        results = []
        for item in items:
            result = (item['ip'], item['port'], item['score'])
            results.append(result)
        return results
    def selectLast(self):
        items = self.tests.find().sort([("chapterID",-1)]).limit(1)
        result = None
        for item in items:
            result = {'chapterID': item['chapterID'],
                      'chapterName': item['chapterName'],
                      'chapterUrl': item['chapterUrl']}

        return result



if __name__ == '__main__':
    from data.MongoHelper import MongoHelper as SqlHelper

    sqlhelper = SqlHelper()
    sqlhelper.init_db('元尊+天蚕土豆')
    tmp = sqlhelper.selectLast()

    print(tmp['chapterID'])

    # for n in ['永夜君王+毛利', '天年+毛利', '庆余年+毛利', '我发的啥+毛利']:
    #     sqlhelper.init_db(str(n))
    #     sqlhelper.insert(value={'chapterID':'1', 'chapterName':'第一章', 'chapterContent':'我是这么写'})